package com.sy.service.impl;

import com.sy.bean.Receipt;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.common.exception.BusinessException;
import com.sy.common.utils.DateUtils;
import com.sy.mapper.GoodsWarehouseStockMapper;
import com.sy.mapper.PurchaseDetailMapper;
import com.sy.mapper.ReceiptDetailMapper;
import com.sy.mapper.ReceiptMapper;
import com.sy.service.ReceiptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class ReceiptServiceImpl extends BaseServiceImpl<Receipt, ReceiptMapper> implements ReceiptService {
    @Autowired
    ReceiptDetailMapper receiptDetailMapper;
    //采购 明细
    @Autowired
    PurchaseDetailMapper purchaseDetailMapper;
    @Autowired
    GoodsWarehouseStockMapper goodsWarehouseStockMapper;

    /**
     * 审核收款单
     * @param id
     * @return
     */
    @Transactional
    @Override
    public int audit(int id) {
        //将付款单状态改为已审核
        int rs = baseMapper.audit(id);
        if (rs == 0)
            throw new BusinessException("审核失败");
        //将 付款单关联的采购单  中采购明细的数量 同步到 明细中对应的仓库
        //根据关联的采购单  查询出对应明细 （商品id  数量   仓库）
        //查询对应采购单相关明细
        List<Map> list = purchaseDetailMapper.queryDetailByPurchaseCode(id);
        //遍历更新对应的库存
        list.forEach(el -> {
            //根据仓库id  商品id做为条件  更新商品仓库库存表 中的数量   goods_warehouse_stock
            //对应商品  在指定仓库有记录 更新数量   如果没有记录  插入新的记录（采购的数量 ）
            Map tmp = (Map) el;
            int result = goodsWarehouseStockMapper.updateStock(tmp);
        });
        return 1;
    }

    /**
     * 保存收款单
     * @param receipt 要保存的对象
     * @return
     */
    @Transactional
    public int save(Receipt receipt) {
        receipt.setCode(generateNum());
        int rs = super.save(receipt);
        if (rs == 0)
            throw new BusinessException("保存收款单据失败");
        //保存收款明细
        if (null == receipt.getReceiptDetailList() || receipt.getReceiptDetailList().size() == 0)
            throw new BusinessException("收款单明细不能为空");
        rs = receiptDetailMapper.batchSave(receipt.getId(), receipt.getReceiptDetailList());
        if (rs == 0)
            throw new BusinessException("收款明细保存失败");
        return 1;
    }

    String generateNum() {
        String time = DateUtils.getSystemTime();
        Random random = new Random();
        int num = random.nextInt(10000);
        return "SKDJ" + time + String.format("%04d", num);
    }

    /**
     * 收款单列表
     */

}
